package com.psct.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.psct.bean.CriRes;
import com.psct.bean.ImageRes;
import com.psct.bean.Mp3Res;
import com.psct.bean.TextRes;
import com.psct.bean.UserAccount;

public class HttpUtil {
	public static final String BASE_URL = "http://192.168.20.214:8080/recallchina";
	private static final String WEBSERVICE_VERSIONINFO_URL = "http://www.12556633.com/ws/ptt_update.xml";
	private static final String TAG = "HttpUtil";
	private Context context;

	public HttpUtil(Context context) {
		this.context = context;
	}

	private static DefaultHttpClient defaultHttpClient;
	private static byte[] b = new byte[] {};

	/**
	 * 取得执行网络访问的公共客户端
	 * 
	 * @return
	 */
	private DefaultHttpClient getHttpClient() {
		if (defaultHttpClient == null) {
			synchronized (b) {
				if (defaultHttpClient == null) {
					HttpParams params = new BasicHttpParams();
					HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
					HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
					HttpProtocolParams.setUseExpectContinue(params, true);

					ConnManagerParams.setTimeout(params, 1000);
					HttpConnectionParams.setConnectionTimeout(params, 5000);
					HttpConnectionParams.setSoTimeout(params, 30 * 1000);

					SchemeRegistry schReg = new SchemeRegistry();
					schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
					schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

					ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params,
							schReg);
					defaultHttpClient = new DefaultHttpClient(connMgr, params);
				}

			}

		}
		return defaultHttpClient;
	}

	/**
	 * 通过课本id查本册课文列表
	 * 
	 * @param userId
	 * @param bookId
	 * @return
	 */
	public TextRes getBook(String userId, String bookId) {
		String URL = BASE_URL + "/LessonServlet?";
		Log.v(TAG, "请求课本数据：bookId:" + bookId + " URL：" + URL);
		HttpPost request = new HttpPost(URL);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("method", "findLesson"));
		// params.add(new BasicNameValuePair("uerId", userId));
		params.add(new BasicNameValuePair("bookId", bookId));
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			request.setEntity(entity);
			HttpResponse response = getHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String back = EntityUtils.toString(response.getEntity());
				Log.v(TAG, back);
				Gson gson = new Gson();
				TextRes res = gson.fromJson(back, new TypeToken<TextRes>() {
				}.getType());
				return res;
			} else {
				Log.v(TAG, "错误结果：" + EntityUtils.toString(response.getEntity()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通过课文id请求课文图片url
	 * 
	 * @param textId
	 * @return
	 */
	public ImageRes getImageUrlListByTextId(int textId) {
		String URL = BASE_URL + "/LessonServlet?";
		Log.v(TAG, "请求图片数据：bookId:" + textId + " URL：" + URL);
		HttpPost request = new HttpPost(URL);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("method", "findImage"));
		params.add(new BasicNameValuePair("textId", textId + ""));
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			request.setEntity(entity);
			HttpResponse response = getHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String back = EntityUtils.toString(response.getEntity());
				Log.v(TAG, back);
				Gson gson = new Gson();
				ImageRes res = gson.fromJson(back, new TypeToken<ImageRes>() {
				}.getType());
				Log.v(TAG, res.urlList.size() + "个");
				return res;
			} else {
				Log.v(TAG, "错误结果：" + EntityUtils.toString(response.getEntity()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 请求评论列表
	 * 
	 * @param textId
	 * @return
	 */
	public CriRes getCriticism(int textId) {
		String URL = BASE_URL + "/LessonServlet?";
		Log.v(TAG, "请求图片数据：bookId:" + textId + " URL：" + URL);
		HttpPost request = new HttpPost(URL);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("method", "findComment"));
		params.add(new BasicNameValuePair("textId", textId + ""));
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			request.setEntity(entity);
			HttpResponse response = getHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String back = EntityUtils.toString(response.getEntity());
				Log.v(TAG, "评论请求结果：" + back);
				Gson gson = new Gson();
				CriRes res = gson.fromJson(back, new TypeToken<CriRes>() {
				}.getType());
				Log.v(TAG, res.criticismList.size() + "个");
				return res;
			} else {
				Log.v(TAG, "错误结果：" + EntityUtils.toString(response.getEntity()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发表评论
	 */
	public String addCriticism(String userId, int textId, String criticism) {
		String URL = BASE_URL + "/CommentServlet?";
		Log.v(TAG, "发表评论：textId:" + textId + " URL：" + URL);
		HttpPost request = new HttpPost(URL);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("method", "addComment"));
		params.add(new BasicNameValuePair("userId", "-1"));
		params.add(new BasicNameValuePair("lessonId", textId + ""));
		params.add(new BasicNameValuePair("content", criticism));
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, "GBK");
			request.setEntity(entity);
			HttpResponse response = getHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String back = EntityUtils.toString(response.getEntity());
				Log.v(TAG, "返回结果：" + back);
				return back;
				// return res;
			} else {
				Log.v(TAG, "错误结果：" + EntityUtils.toString(response.getEntity()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 登录
	 * 
	 * @param account
	 * @param pwd
	 * @return
	 */
	public UserAccount login(String account, String pwd) {
		String URL = BASE_URL + "/UserServlet?";
		Log.v(TAG, "登录：account:" + account + " pwd：" + pwd);
		HttpPost request = new HttpPost(URL);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("method", "login"));
		params.add(new BasicNameValuePair("userName", account));
		params.add(new BasicNameValuePair("password", pwd));
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			request.setEntity(entity);
			HttpResponse response = getHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String back = EntityUtils.toString(response.getEntity());
				Log.v(TAG, "返回结果：" + back);
				Gson gson = new Gson();
				UserAccount res = gson.fromJson(back, new TypeToken<UserAccount>() {
				}.getType());
				return res;
			} else {
				Log.v(TAG, "错误结果：" + EntityUtils.toString(response.getEntity()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (com.google.gson.JsonSyntaxException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 注册
	 * 
	 * @param account
	 * @param pwd
	 * @return
	 */
	public String regist(String account, String pwd) {
		String URL = BASE_URL + "/UserServlet?";
		Log.v(TAG, "注册用户：account:" + account + " pwd：" + pwd);
		HttpPost request = new HttpPost(URL);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("method", "addUser"));
		params.add(new BasicNameValuePair("userName", account));
		params.add(new BasicNameValuePair("password", pwd));
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, "GBK");
			request.setEntity(entity);
			HttpResponse response = getHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String back = EntityUtils.toString(response.getEntity());
				Log.v(TAG, "返回结果：" + back);
				return back;
				// return res;
			} else {
				Log.v(TAG, "错误结果：" + EntityUtils.toString(response.getEntity()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Mp3Res getBgMusicList() {
		String URL = BASE_URL + "/MusicServlet?";
		Log.v(TAG, "请求mp3列表");
		HttpPost request = new HttpPost(URL);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("method", "findMusic"));
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, "GBK");
			request.setEntity(entity);
			HttpResponse response = getHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String back = EntityUtils.toString(response.getEntity());
				Log.v(TAG, "返回结果：" + back);
				Gson gson = new Gson();
				return gson.fromJson(back, new TypeToken<Mp3Res>() {}.getType());
				// return res;
			} else {
				Log.v(TAG, "错误结果：" + EntityUtils.toString(response.getEntity()));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
